﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Linq;
using System.Text;

namespace Infrastructure.Cache
{
    public class SessionCache:BaseCache
    {
        private const string SESSION_CACHE_OBJECT_KEY = "_SESSION_CACHE_";
        private static SessionCache clientInstance = null;
        private static Dictionary<string, object> dictCache = new Dictionary<string,object>();
        public static SessionCache Instance
        {
            get
            {
                SessionCache instance = null;
                if (System.Web.HttpContext.Current != null)
                {
                    instance = HttpContext.Current.Session[SESSION_CACHE_OBJECT_KEY] as SessionCache;
                    if (instance == null) HttpContext.Current.Session[SESSION_CACHE_OBJECT_KEY] = (instance = new SessionCache());
                    return instance;
                }
                else
                {
                    if (clientInstance == null) clientInstance = new SessionCache();
                    instance = clientInstance;
                }
                return instance;
            }
        }

        public override string[] Keys
        {
            get
            {
                if(HttpContext.Current.Session != null)
                {
                    System.Collections.IEnumerator enumerator = HttpContext.Current.Session.Keys.GetEnumerator();
                    string[] keys = new string[HttpContext.Current.Session.Count];
                    int index = 0;
                    while (enumerator.MoveNext()) keys[index++] = enumerator.Current.ToString();
                    return keys;
                }
                else
                {
                    return dictCache.Keys.ToArray();
                }
            }
        }

        public override object this[string key]
        {
            get { 
                if(HttpContext.Current.Session != null)  return HttpContext.Current.Session[key];
                else if (dictCache.ContainsKey(key)) return dictCache[key];
                return null;
            }
            set { 
                if(HttpContext.Current.Session != null)  HttpContext.Current.Session[key] = value;
                else dictCache[key] = value;
            }
        }

        public override void Remove(string key)
        {
            if(HttpContext.Current.Session != null)  HttpContext.Current.Session.Remove(key);
            else if(dictCache.ContainsKey(key)) dictCache.Remove(key);
        }
    }
}
